<template>
	<div v-loading="loading" class="app-main-content-box">
		<!-- 头部 -->
		<div class="app-main-top-box">
			<app-main-title :title="(mode === 'add' ? `添加卡：` : '编辑卡：') + cardTypeOptions[form.cardType]" />
			<el-button size="medium" round @click="back">返回</el-button>
		</div>

		<!-- 步骤条 start -->
		<div class="step-container">
			<el-steps :active="step">
				<el-step title="基础信息" description="配置卡券的基础信息" />
				<el-step title="发放和核销" description="投放和核销的规则" />
				<el-step title="样式主题" description="管理顾客端效果" />
				<el-step title="确认创建" description="检查并完成创建" />
			</el-steps>
		</div>
		<!-- 步骤条 end -->

		<!-- 表单 start -->
		<el-form ref="form" :model="form" :rules="rules" label-suffix="：" label-width="170px" size="small">
			<!-- step 0 start -->
			<div v-show="step === 0">
				<div>
					<!-- 卡名称 -->
					<el-form-item label="卡名称" prop="cardName">
						<el-input v-model.trim="form.cardName" placeholder="请输入卡名称" class="w-400" />
					</el-form-item>

					<!-- 卡次数 -->
					<el-form-item v-if="form.cardType === 'times'" label="卡次数" prop="times">
						<el-input v-model.trim="form.times" maxlength="8" placeholder="请输入" class="w-170">
							<template slot="append">
								次
							</template>
						</el-input>
					</el-form-item>

					<!-- 卡面额 -->
					<el-form-item v-if="form.cardType === 'gift'" label="卡金额" prop="denomination">
						<el-input v-model.trim="form.denomination" maxlength="9" placeholder="请输入" class="w-170">
							<template slot="append">
								元
							</template>
						</el-input>
					</el-form-item>

					<!-- 可用时间 -->
					<el-form-item label="可用时间" class="is-required">
						<el-form-item prop="date">
							<el-date-picker v-model="form.date" :picker-options="datePickerOptions"
								:default-time="['00:00:00', '23:59:59']" type="daterange" range-separator="~"
								start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"
								format="yyyy-MM-dd" />
						</el-form-item>

						<!-- 时间类型 -->
						<el-form-item>
							<el-select v-model="form.availableTime.timeType" placeholder="请选择" style="width:350px">
								<template v-for="item in useRuleOptions">
									<el-option v-if="item.value !== 3" :key="item.value" :label="item.label"
										:value="item.value" />
									<el-option
										v-if="item.value === 3 && ['cash', 'discount', 'exchange'].includes(form.couponType)"
										:key="item.value" :label="item.label" :value="item.value" />
								</template>
							</el-select>
						</el-form-item>

						<!-- 时间类型一 -->
						<el-collapse-transition>
							<div v-if="form.availableTime.timeType === 1" class="nest-card-box">
								<el-card>
									<div>
										<span>生效后&nbsp;</span>
										<el-form-item prop="availableTime.days" style="display:inline-block">
											<el-input v-model="form.availableTime.days" placeholder="请输入" class="w-170">
												<template slot="append">
													天
												</template>
											</el-input>
										</el-form-item>
										<span>&nbsp;内可使用</span>
									</div>
									<div class="tips-text">
										用户在活动有效期开始前领取卡，则从活动有效期第一天开始计算天数
										<br />
										用户在活动有效期内领取代金卡，则从领取当天开始计算天数
										<br />
										无论用户何时领取代卡，卡在活动有效期结束后均不可用
									</div>
								</el-card>
							</div>
						</el-collapse-transition>

						<!-- 时间类型 234 -->
						<el-collapse-transition>
							<div v-if="[2, 3, 4].includes(form.availableTime.timeType)" class="nest-card-box">
								<el-card>
									<el-form-item v-if="form.availableTime.timeType === 2"
										prop="availableTime.availablePeriodWeek">
										<el-checkbox-group v-model="form.availableTime.availablePeriodWeek">
											<el-checkbox-button v-for="(weekItem, weekIndex) in weekOptions"
												:key="'week-' + weekIndex" :label="String(weekItem.value)">
												{{ weekItem.label }}
											</el-checkbox-button>
										</el-checkbox-group>
									</el-form-item>
									<div v-if="form.availableTime.timeType === 3">
										<div class="tips-text">选择日期后，每一个自然月的当天都可使用</div>
										<el-form-item prop="availableTime.availablePeriodDay">
											<el-checkbox-group v-model="form.availableTime.availablePeriodDay"
												class="day-box">
												<el-checkbox-button v-for="(dayItem, dayIndex) in 31"
													:key="'day-' + dayIndex" :label="String(dayItem)">
													{{ dayItem }}
												</el-checkbox-button>
											</el-checkbox-group>
										</el-form-item>
									</div>
									<div v-if="form.availableTime.timeType === 4">
										<div class="tips-text">
											可在有效期内任意选择时间天数，以及可用时段。
											<br />
											因当前系统支持问题，如选择不规则时间，卡包内当前仅会展示有效期，建议
											<br />
											将具体可用日期以及时间段填写在卡使用说明内。
											<br />
										</div>

										<el-form-item prop="availableTime.availableDateList">
											<div v-for="(item, index) in form.availableTime.availableDateList"
												:key="'date' + index" style="margin-top:18px">
												<el-date-picker
													v-model="form.availableTime.availableDateList[index].date"
													type="daterange" range-separator="~" start-placeholder="开始日期"
													end-placeholder="结束日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
													size="small" />
												<el-button v-if="form.availableTime.availableDateList.length > 1"
													type="text" icon="el-icon-delete" class="app-text-color-danger"
													@click="delAvailableDateList(index)">
													删除
												</el-button>
												<el-button
													v-if="form.availableTime.availableDateList.length === index + 1 && form.availableTime.availableDateList.length < 3"
													type="text" icon="el-icon-plus" class="app-text-color-primary"
													@click="addAvailableDateList">
													添加
												</el-button>
											</div>
										</el-form-item>
									</div>
									<el-form-item prop="availableTime.availableTimeList">
										<div v-for="(item, index) in form.availableTime.availableTimeList"
											:key="'time' + index" style="margin-top:18px">
											<el-time-picker v-model="form.availableTime.availableTimeList[index].time"
												is-range value-format="HH:mm" format="HH:mm" range-separator="~"
												start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围" />
											<el-button v-if="form.availableTime.availableTimeList.length > 1"
												type="text" icon="el-icon-delete" class="app-text-color-danger"
												@click="delAvailableTimeList(index)">
												删除
											</el-button>
											<el-button
												v-if="form.availableTime.availableTimeList.length === index + 1 && form.availableTime.availableTimeList.length < 3"
												type="text" icon="el-icon-plus" class="app-text-color-primary"
												@click="addAvailableTimeList">
												添加
											</el-button>
										</div>
									</el-form-item>
									<div class="tips-text">请按照24小时制输入可用时段，最多设置3个时段</div>
								</el-card>
							</div>
						</el-collapse-transition>
					</el-form-item>

					<!-- 生效时间 -->
					<!--v-if="form.availableTime.timeType===1"-->
					<div>
						<el-form-item label="生效时间" class="is-required">
							<el-select v-model="form.secondDayAvailable" placeholder="请选择" class="w-400">
								<el-option :value="false" label="领取后立即生效" />
								<el-option :value="true" label="领取后第二天生效" />
							</el-select>
						</el-form-item>
					</div>

					<!-- 说明 -->
					<el-form-item label="使用说明">
						<el-input v-model="form.description" :autosize="{ minRows: 2, maxRows: 10 }" type="textarea"
							maxlength="1024" show-word-limit placeholder="请输入" class="nest-card-box"
							style="margin-left:0" />
					</el-form-item>
				</div>
			</div>
			<!-- step 0 end -->

			<!-- step 1 start -->
			<div v-show="step === 1">
				<!-- 用户限制 -->
				<el-form-item label="用户限制">
					<el-form-item prop="maxUseDay">
						<el-checkbox v-model="form.maxUseDayChecked">设置一个自然日单用户可使用&nbsp;</el-checkbox>
						<el-input v-model="form.maxUseDay" :disabled="!form.maxUseDayChecked" placeholder="请输入"
							maxlength="10" class="w-200">
							<template v-if="['times'].includes(form.cardType)" slot="append">
								次
							</template>
							<template v-if="['gift'].includes(form.cardType)" slot="append">
								元
							</template>
						</el-input>
					</el-form-item>
					<el-form-item prop="maxUseWeek">
						<el-checkbox v-model="form.maxUseWeekChecked">设置一个自然周单用户可使用&nbsp;</el-checkbox>
						<el-input v-model="form.maxUseWeek" :disabled="!form.maxUseWeekChecked" placeholder="请输入"
							maxlength="10" class="w-200">
							<template v-if="['times'].includes(form.cardType)" slot="append">
								次
							</template>
							<template v-if="['gift'].includes(form.cardType)" slot="append">
								元
							</template>
						</el-input>
					</el-form-item>
					<el-form-item prop="maxUseMonth">
						<el-checkbox v-model="form.maxUseMonthChecked">设置一个自然月单用户可使用&nbsp;</el-checkbox>
						<el-input v-model="form.maxUseMonth" :disabled="!form.maxUseMonthChecked" placeholder="请输入"
							maxlength="10" class="w-200">
							<template v-if="['times'].includes(form.cardType)" slot="append">
								次
							</template>
							<template v-if="['gift'].includes(form.cardType)" slot="append">
								元
							</template>
						</el-input>
					</el-form-item>
				</el-form-item>

				<!-- 核销商户 -->
				<el-form-item label="核销商户" prop="verifyMerchant">
					<el-select v-model="form.verifyMerchant" placeholder="请选择" class="w-400">
						<el-option :value="1" label="本商户下所有店铺" />
						<el-option :value="2" label="本商户和已合作商户的所有店铺" />
						<el-option :value="3" label="指定本商户和已合作商户的部分店铺" />
					</el-select>
					<el-form-item style="display: inline-block;min-width: 100px" prop="verifyMerchantList">
						<el-button v-if="form.verifyMerchant === 3 || form.verifyMerchant === 4"
							@click="openDialogMerchantsTree('verifyMerchant')">
							<span v-if="form.verifyMerchantList.length">
								已选择&nbsp;
								<span class="app-text-color-danger">{{ form.verifyMerchantList.length }}</span>
								&nbsp;家商户
							</span>
							<span v-else>选择</span>
						</el-button>
					</el-form-item>
				</el-form-item>
				<!-- 提醒规则 -->
				<el-form-item v-if="['times'].includes(form.cardType)" label="提醒规则" prop="verifyMerchant1">
					<el-checkbox v-model="form.noticeCycleFlg" true-label="Y" false-label="N">开启下次到店消费提醒</el-checkbox>
					<div v-show="form.noticeCycleFlg == 'Y'">
						<div class="tips-text">
							<div>若开启后，则会在设定的时间给用户发送建议下次到店消费日期，发送时间为到店时间的前一天开始逐个发送。设置为7天，发送规则如下：</div>
							<div>
								1.下次到店日期：开始日期+设置天数，未核销时，开始日期为最后提醒日期/生效日期的最新日期，如设置7天，发放日期为09月01日，生效日期为09月15日，则在09月21日发送消息提醒用户于09月22日到店消费。
							</div>
							<div>
								2.提醒日期：开始日期+设置天数-1，核销后，开始日期为核销日期的最新日期，如设置7天，09月16日核销成功后，则09月22日发送消息提醒用户于09月23日到店消费。
							</div>
						</div>
						<div>
							提醒用户每间隔
							<el-input-number v-model="form.noticeCycleDays" controls-position="right" :min="1" :max="10"
								:precision="0" :step="1" />
							天到店消费1次
						</div>
						<div class="tips-text">
							<div>温馨提示：</div>
							<div>1.预计每天10点发送消息，可能会有所延迟，以实际发送时间为准；</div>
							<div>2.若下次的日期大于等于次卡过期的结束日期，则按照过期当天日期发送提醒，即用户需在次卡过期当天到店消息；</div>
							<div>3.最后一次核销不会再发送提醒消息。</div>
						</div>
					</div>
				</el-form-item>
				<div v-if="['gift'].includes(form.cardType)">
					<!-- 核销业务 -->
					<el-form-item item label="核销业务" class="is-required">
						<el-select v-model="form.verifyBusinessType" placeholder="请选择" class="w-400">
							<el-option :value="1" label="所有的业务场景下可核销" />
							<el-option :value="2" label="指定部分业务场景下可核销" />
						</el-select>
						<el-collapse-transition>
							<div v-if="form.verifyBusinessType === 2" class="nest-card-box" style="margin-top:10px">
								<el-card :body-style="{ padding: '20px 20px 0 20px' }">
									<el-form-item prop="verifyBusiness">
										<el-checkbox-group v-model="form.verifyBusiness">
											<template v-for="item in manageBizCodeOptions">
												<el-checkbox
													v-if="(item.usePay && item.canDiscount) || item.key == 9056"
													:key="item.value" :label="String(item.key)">
													{{ item.label }}
												</el-checkbox>
											</template>
										</el-checkbox-group>
									</el-form-item>
								</el-card>
							</div>
						</el-collapse-transition>
					</el-form-item>

					<!--优惠标志-->
					<el-form-item label="订单优惠标记" prop="discountTag">
						<el-tag v-for="(v, i) in form.discountTag" :key="'discountTag-' + i"
							:disable-transitions="false" closable @close="closeDiscountTag(i)">{{ v }}</el-tag>
						<el-input ref="discountTagInput" v-model.trim="discountTagInputValue" class="w-400-h-32"
							size="small" placeholder="请输入标记" maxlength="10" show-word-limit
							@keyup.enter.native="addDiscountTag" @blur="addDiscountTag" />
						<div class="tips-text">输入后按Enter回车新增，填写后，需要订单具备该标记才可使用卡</div>
					</el-form-item>
				</div>
			</div>
			<!-- step 1 end -->

			<!-- step 2 start -->
			<!-- 背景主题 -->
			<div v-show="step === 2">
				<el-form-item label="背景主题" prop="theme">
					<div class="flexRSC">
						<el-color-picker v-model="form.theme" :predefine="predefineColors"
							popper-class="theme-picker-dropdown" />
						<span>&nbsp;{{ form.theme }}</span>
					</div>
				</el-form-item>

				<!-- 品牌名称 -->
				<el-form-item label="品牌名称" prop="brandName">
					<el-input v-model="form.brandName" placeholder="不填写默认使用本商户号名称" maxlength="12" show-word-limit
						style="width:400px" />
				</el-form-item>

				<!-- LOGO -->
				<el-form-item label="LOGO" prop="logo">
					<div class="upload-container">
						<el-upload :action="imageUploadUrl" :show-file-list="false"
							:headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }" :before-upload="
								file => {
									return handleImgBefore(file, 1);
								}
							" :on-success="
								(res, file) => {
									return handleImgSuccess(res, file, 'logo');
								}
							" class="app-uploader-img-plus" style="width:120px;height:120px">
							<el-image v-if="form.logo" :src="fileBaseUrl + form.logo" style="width:120px;height:120px"
								class="img" fit="fill" />
							<i v-else class="el-icon-plus" style="width:120px;height:120px" />
						</el-upload>
						<el-button v-if="form.logo" type="text" size="small" style="margin-left: 10px"
							class="app-text-color-danger" @click="form.logo = ''">删除LOGO</el-button>
					</div>
					<div class="tips-text">图片建议尺寸：120*120像素，大小不超过1M，支持JPG、PNG，如果不传默认使用当前类型的LOGO。</div>
				</el-form-item>

				<!-- 详情封面 -->
				<el-form-item label="详情封面" prop="detailPage">
					<div class="upload-container">
						<el-upload :action="imageUploadUrl" :show-file-list="false"
							:headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }" :before-upload="
								file => {
									return handleImgBefore(file, 2);
								}
							" :on-success="
								(res, file) => {
									return handleImgSuccess(res, file, 'detailPage');
								}
							" class="app-uploader-img-plus" style="width:320px;height:200px">
							<el-image v-if="form.detailPage" :src="fileBaseUrl + form.detailPage"
								style="width:320px;height:200px" class="img" fit="fill" />
							<i v-else class="el-icon-plus" style="width:320px;height:200px" />
						</el-upload>
						<el-button v-if="form.detailPage" type="text" size="small" style="margin-left: 10px"
							class="app-text-color-danger" @click="form.detailPage = ''">
							删除封面
						</el-button>
					</div>
					<div class="tips-text">图片建议尺寸：850*350像素，大小不超过2M，支持JPG、PNG。</div>
				</el-form-item>

				<!-- 条码显示 -->
				<el-form-item label="条码显示" prop="scanCode" class="is-required">
					<el-select v-model="form.scanCode" placeholder="请选择" class="w-400">
						<el-option :value="3" label="条形码和二维码" />
						<el-option :value="1" label="显示条形码" />
						<el-option :value="2" label="显示二维码" />
					</el-select>
				</el-form-item>

				<!-- 功能按钮 -->
				<div>
					<el-form-item label="功能按钮" prop="functionButton" class="is-required">
						<el-select v-model="form.functionButton" placeholder="请选择" class="w-400">
							<el-option :value="false" label="不显示功能按钮" />
							<el-option :value="true" label="显示功能按钮" />
						</el-select>
					</el-form-item>
					<div v-if="form.functionButton">
						<!-- 按钮文案 -->
						<el-form-item label="按钮文案" prop="functionButtonConfig.word">
							<el-input v-model="form.functionButtonConfig.word" placeholder="请输入" style="width:400px" />
						</el-form-item>

						<!-- 小程序APPID -->
						<el-form-item label="小程序APPID" prop="functionButtonConfig.appId">
							<el-input v-model="form.functionButtonConfig.appId" placeholder="请输入" style="width:400px" />
						</el-form-item>

						<!-- 小程序路径 -->
						<el-form-item label="小程序路径" prop="functionButtonConfig.page">
							<el-input v-model="form.functionButtonConfig.page" placeholder="请输入" style="width:400px" />
						</el-form-item>
					</div>
				</div>
			</div>
			<!-- step 2 end -->

			<!-- step 3 end -->
			<div v-if="step === 3">
				<!--        <el-form-item label="归属商户号">{{ submitForm.belongMerchant }}</el-form-item>-->
				<el-form-item v-if="submitForm.belongMerchantName" label="归属商户名">{{ submitForm.belongMerchantName }}
				</el-form-item>
				<el-form-item label="卡类型">{{ cardTypeOptions[submitForm.cardType] }}</el-form-item>
				<el-form-item label="卡名称">{{ submitForm.cardName }}</el-form-item>
				<el-form-item v-if="['gift'].includes(submitForm.cardType)" label="卡面额">
					{{ submitForm.denomination / 100 }} 元
				</el-form-item>
				<el-form-item v-if="['times'].includes(submitForm.cardType)" label="卡次数">{{ submitForm.times }} 次
				</el-form-item>
				<el-form-item label="可用时间">
					<!-- 总时间 -->
					<div>{{ submitForm.startTime + ' ~ ' + submitForm.endTime }}</div>
					<!-- 时间类型一 -->
					<div v-if="submitForm.availableTime.timeType === 5">有效期内，任意时段可用</div>
					<div v-if="submitForm.availableTime.timeType === 1">生效后 {{ submitForm.availableTime.days }} 天可用
					</div>
					<div v-if="submitForm.availableTime.timeType === 2">
						每周指定星期：{{ submitForm.availableTime.availablePeriod | weekNum2WeekStr }}</div>
					<div v-if="submitForm.availableTime.timeType === 3">
						每月指定日期：{{ submitForm.availableTime.availablePeriod | dayNum2DayStr }}</div>
					<div v-if="submitForm.availableTime.timeType === 4">
						范围内指定日期：
						{{
							submitForm.availableTime.dateList
								.split(',')
								.map(function fun(v) {
									return v.replace(':', ' ~ ');
								})
								.join('、')
						}}
					</div>
					<div
						v-if="submitForm.availableTime.timeType === 2 || submitForm.availableTime.timeType === 3 || submitForm.availableTime.timeType === 4">
						<div v-if="submitForm.availableTime.startMinute1 || submitForm.availableTime.endMinute1">
							{{ submitForm.availableTime.startMinute1 | mm2HHmm }} ~
							{{ submitForm.availableTime.endMinute1 | mm2HHmm }}
						</div>
						<div v-if="submitForm.availableTime.startMinute2 || submitForm.availableTime.endMinute2">
							{{ submitForm.availableTime.startMinute2 | mm2HHmm }} ~
							{{ submitForm.availableTime.endMinute2 | mm2HHmm }}
						</div>
						<div v-if="submitForm.availableTime.startMinute3 || submitForm.availableTime.endMinute3">
							{{ submitForm.availableTime.startMinute3 | mm2HHmm }} ~
							{{ submitForm.availableTime.endMinute3 | mm2HHmm }}
						</div>
					</div>
				</el-form-item>
				<!--v-if="submitForm.availableTime.timeType===1"-->
				<el-form-item label="生效时间">
					<div v-if="submitForm.secondDayAvailable">领取后第二天生效</div>
					<div v-else>领取后立即生效</div>
				</el-form-item>
				<el-form-item label="使用说明">
					<ul v-if="submitForm.description">
						<li v-for="(v, i) in submitForm.description.split(/[(\r\n)]+/)" :key="i">{{ v }}</li>
					</ul>
					<div v-else>无</div>
				</el-form-item>
				<el-form-item label="用户限制">
					<div v-if="submitForm.maxUseDay">
						一个自然日单用户可使用：
						<span v-if="['times'].includes(submitForm.cardType)">{{ submitForm.maxUseDay }} 次</span>
						<span v-if="['gift'].includes(submitForm.cardType)">{{ submitForm.maxUseDay / 100 }} 元</span>
					</div>
					<div v-else>一个自然日单用户可使用：无限制</div>
					<div v-if="submitForm.maxUseWeek">
						一个自然周单用户可使用：
						<span v-if="['times'].includes(submitForm.cardType)">{{ submitForm.maxUseWeek }} 次</span>
						<span v-if="['gift'].includes(submitForm.cardType)">{{ submitForm.maxUseWeek / 100 }} 元</span>
					</div>
					<div v-else>一个自然周单用户可使用：无限制</div>
					<div v-if="submitForm.maxUseMonth">
						一个自然月单用户可使用：
						<span v-if="['times'].includes(submitForm.cardType)">{{ submitForm.maxUseMonth }} 次</span>
						<span v-if="['gift'].includes(submitForm.cardType)">{{ submitForm.maxUseMonth / 100 }} 元</span>
					</div>
					<div v-else>一个自然月单用户可使用：无限制</div>
				</el-form-item>
				<el-form-item label="核销商户">
					<div v-if="submitForm.verifyMerchant === 1">本商户下所有店铺</div>
					<div v-else-if="submitForm.verifyMerchant === 2">本商户和已合作商户的所有店铺</div>
					<div v-else-if="submitForm.verifyMerchant === 3">
						<template v-for="v in submitForm.verifyMerchantList">
							<span :key="v.merchant" class="last-dot">
								<span>{{ v.merchantName }}</span>
								<span class="dot">、</span>
							</span>
						</template>
					</div>
				</el-form-item>

				<el-form-item v-if="['times'].includes(submitForm.cardType)" label="提醒规则" prop="verifyMerchant1">
					<div v-if="submitForm.noticeCycleFlg == 'Y'">提醒用户每间隔{{ submitForm.noticeCycleDays }}天到店消费1次</div>
					<div v-else>无</div>
				</el-form-item>

				<div v-if="['gift'].includes(submitForm.cardType)">
					<el-form-item label="核销业务">
						<template v-if="submitForm.verifyBusiness">
							<template v-for="v in submitForm.verifyBusiness.split(',')">
								<span :key="v" class="last-dot">
									<span>{{ bizCodeKeyOptions[v] }}</span>
									<span class="dot">、</span>
								</span>
							</template>
						</template>
						<span v-else>所有业务</span>
					</el-form-item>
					<el-form-item label="订单优惠标记">
						{{ submitForm.discountTag ? submitForm.discountTag.replace(/,/g, '、') : '无' }}
					</el-form-item>
				</div>
				<el-form-item label="背景主题">
					<div class="flexRSC">
						<span :style="{ backgroundColor: submitForm.theme, height: '22px', width: '22px' }" />
						&nbsp;
						<span>{{ submitForm.theme }}</span>
					</div>
				</el-form-item>
				<el-form-item label="品牌名称">{{ submitForm.brandName }}</el-form-item>
				<el-form-item label="LOGO">
					<el-image v-if="submitForm.logo" :src="fileBaseUrl + submitForm.logo"
						style="width:120px;height:120px" fit="fill" />
					<el-image v-else :src="'static/icon/coupon/i-card-' + submitForm.cardType + '.png'"
						style="width:120px;height:120px" fit="fill" />
				</el-form-item>
				<el-form-item label="详情封面">
					<el-image v-if="submitForm.detailPage" :src="fileBaseUrl + submitForm.detailPage"
						style="width:320px;height:200px" fit="fill" />
					<span v-else>无</span>
				</el-form-item>
				<el-form-item label="条码显示">
					<div v-if="submitForm.scanCode === 1 || submitForm.scanCode === 3">显示条形码</div>
					<div v-if="submitForm.scanCode === 2 || submitForm.scanCode === 3">显示二维码</div>
					<div />
				</el-form-item>
				<el-form-item label="功能按钮">
					<div v-if="!submitForm.functionButton">不显示功能按钮</div>
					<div v-else>
						<div>文案：{{ JSON.parse(submitForm.functionButtonConfig).word || '无' }}</div>
						<div>appid：{{ JSON.parse(submitForm.functionButtonConfig).appId || '无' }}</div>
						<div>路径：{{ JSON.parse(submitForm.functionButtonConfig).page || '无' }}</div>
					</div>
				</el-form-item>
			</div>
			<!-- step 3 end -->

			<el-form-item>
				<el-button v-if="1 <= step && step <= 3" round @click="changeStep('sub')">上一步</el-button>
				<el-button v-if="step === 3" type="primary" round @click="submit('save', 'draft')">保存至草稿箱</el-button>
				<el-button v-if="step === 3" type="primary" round @click="submit('save', 'on')">保存并启用</el-button>
				<!-- <el-button v-if="step===3" type="primary" round @click="submit('use')">保存并激活</el-button> -->
				<el-button v-if="step !== 3" round @click="changeStep('add')">下一步</el-button>
			</el-form-item>
		</el-form>

		<!-- 本商户门店弹框 -->
		<DialogMerchantsTree ref="dialogMerchantsTree" />
	</div>
</template>

<script>
	import DialogMerchantsTree from '../components/DialogMerchantsTree';
	import FormValidate from './mixin/FormValidate';
	import {
		mapGetters
	} from 'vuex';
	import {
		imgUploadUrl
	} from '@/api/upload';
	import {
		saveCard,
		saveAndOpenUpCard,
		cardDetail
	} from '../../api/card';
	import {
		authMerchants
	} from '../../api/mch';

	export default {
		components: {
			DialogMerchantsTree
		},
		mixins: [FormValidate],
		data() {
			const _this = this;
			return {
				// 配置
				cardTypeOptions: {
					times: '次卡',
					gift: '礼品卡'
				},
				weekOptions: [{
						label: '周一',
						value: 2
					},
					{
						label: '周二',
						value: 3
					},
					{
						label: '周三',
						value: 4
					},
					{
						label: '周四',
						value: 5
					},
					{
						label: '周五',
						value: 6
					},
					{
						label: '周六',
						value: 7
					},
					{
						label: '周日',
						value: 1
					}
				],
				useRuleOptions: [{
						value: 5,
						label: '有效期内，任意时段可用'
					},
					{
						value: 1,
						label: '有效期内，生效后N天可用'
					},
					{
						value: 2,
						label: '有效期内，规则星期可用'
					},
					{
						value: 3,
						label: '有效期内，规则日期可用'
					},
					{
						value: 4,
						label: '有效期内，不规则日期可用'
					}
				],
				predefineColors: ['#63B359', '#2C9F67', '#509FC9', '#5885CF', '#9062C0', '#D09A45', '#E4B138', '#EE903C',
					'#DD6549', '#CC463D'
				],
				datePickerOptions: {
					disabledDate(time) {
						return _this
							.$momentMini()
							.subtract(1, 'days')
							.isAfter(time);
					}
				},
				imageUploadUrl: imgUploadUrl,
				// 状态
				loading: false,
				// 数据
				mode: 'add',
				cardType: 'times',
				step: 0,
				categoryList: [],
				discountTagInputValue: null, // tag值
				cardId: null,
				form: {
					belongMerchant: null, // 归属商户号
					cardName: null,
					cardType: 'times',
					times: null, // 次数
					denomination: null, // 面额
					availableTime: {
						timeType: 5, // 日期类型 1：领券后N天可用，2：规则星期可用，3：规则日期可用，4：不规则日期可用' 5:所有时间
						days: null, // 1：领券后N天可用
						availablePeriodWeek: [], // 2： 有效周 1星期天 no params 需转availablePeriod ,分割string
						availablePeriodDay: [], // 3：有效日 1~31日 no params 需转availablePeriod ,分割string
						availablePeriod: null, // 2： 有效周 3：有效日
						availableDateList: [{
							date: null
						}], // 有效日期  no params 需转dateList yyyy-MM-dd:yyyy-MM-dd,yyyy-MM-dd:yyyy-MM-dd
						dateList: null,
						availableTimeList: [{
							time: ['00:00', '23:59']
						}], // 有效时间 转start_minute1 end_minute1
						startMinute1: null,
						endMinute1: null,
						startMinute2: null,
						endMinute2: null,
						startMinute3: null,
						endMinute3: null
					},
					secondDayAvailable: false, // 生效时间
					description: null, // 使用说明
					maxUseDayChecked: false, // 是否勾选  no params
					maxUseDay: null, // 用户日预算
					maxUseWeekChecked: false, // 是否勾选  no params
					maxUseWeek: null, // 用户周预算
					maxUseMonthChecked: false, // 是否勾选  no params
					maxUseMonth: null, // 用户月预算
					verifyMerchant: 1, // 核销商户类型 1本商户  2本商户和所有合作商户 3本商户与合作商户指定门店  4本商户指定店铺
					verifyMerchantList: [],
					noticeCycleFlg: 'Y',
					noticeCycleDays: 7,
					verifyBusinessType: 1, // 业务类型 no params  1：所有 2：部分
					verifyBusiness: [], // 业务类型  需转,分割string
					discountTag: [], // 优惠标记 需转str
					theme: '#63B359', // 主题色
					brandName: null, // 品牌名称
					logo: null, // LOGO
					detailPage: null, // 详情封面链接
					scanCode: 3, // 条码显示 1：条形码，2：二维码，3：二者
					functionButton: false, // 功能
					// 按钮内容 需转string
					functionButtonConfig: {
						word: null, // 按钮文案
						appId: null, // appid
						page: null // 页面路径
					}
				},
				submitForm: null
			};
		},
		computed: {
			...mapGetters(['manageBizCodeOptions', 'bizCodeKeyOptions', 'fileBaseUrl', 'businessInfo'])
		},
		watch: {},
		beforeCreate() {},
		created() {},
		beforeMount() {},
		mounted() {
			const queryParams = this.$route.query;
			if (queryParams.mode === 'add' && queryParams.cardType) {
				this.form.cardType = queryParams.cardType;
				//  判断是否有携带商户参数
				if (queryParams.belongMerchant && queryParams.belongMerchantName) {
					this.activeBusinessInfo = {
						id: queryParams.belongMerchant,
						name: queryParams.belongMerchantName
					};
					this.form.belongMerchant = queryParams.belongMerchant;
				} else {
					this.activeBusinessInfo = this.businessInfo;
					this.form.belongMerchant = this.businessInfo.id;
				}
			} else if (queryParams.mode === 'edit' && queryParams.id) {
				this.mode = queryParams.mode;
				this.cardId = queryParams.id;
			}
			this.fetchData();
		},
		beforeUpdate() {},
		update() {},
		activated() {},
		deactivated() {},
		beforeDestroy() {},
		destroyed() {},
		methods: {
			/**
			 * 数据组
			 */
			// 初始化数据
			fetchData() {
				this.loading = true;
				if (this.cardId) {
					Promise.all([this.getDetail()]).finally(() => {
						this.getAuthMerchants();
						this.loading = false;
					});
				} else {
					Promise.all([this.getAuthMerchants()]).finally(() => {
						this.loading = false;
					});
				}
			},

			// 获取合作商户
			getAuthMerchants() {
				return new Promise(resolve => {
					if (this.form.belongMerchant) {
						authMerchants({
								belongMerchant: this.form.belongMerchant
							})
							.then(res => {
								const allMchList = [];
								res.data.forEach(v => {
									v.id = 'M-' + v.id;
									allMchList.push({
										id: v.id,
										name: v.name,
										shops: []
									});
								});
								this.allMchList = allMchList;
								this.allMchShopList = res.data;
							})
							.finally(() => {
								resolve();
							});
					} else {
						resolve();
					}
				});
			},

			// 获取详情
			getDetail() {
				return new Promise(resolve => {
					cardDetail({
							cardId: this.cardId
						})
						.then(res => {
							const params = res.data.prototype;
							params.availableTime = res.data.availableTime;
							params.verifyMerchantList = res.data.verifyMerchantList;
							console.log('原数据', params);

							// 格式化预算
							params.maxUseDayChecked = !!params.maxUseDay;
							params.maxUseWeekChecked = !!params.maxUseWeek;
							params.maxUseMonthChecked = !!params.maxUseMonth;
							// 次卡
							if (['times'].includes(params.cardType)) {
								params.verifyBusinessType = 1;
								params.verifyBusiness = [];
							}

							// 礼品卡
							if (['gift'].includes(params.cardType)) {
								params.denomination = params.denomination / 100;
								params.maxUseDay = params.maxUseDay ? params.maxUseDay / 100 : 0;
								params.maxUseWeek = params.maxUseWeek ? params.maxUseWeek / 100 : 0;
								params.maxUseMonth = params.maxUseMonth ? params.maxUseMonth / 100 : 0;
								// 核销业务
								if (params.verifyBusiness) {
									params.verifyBusiness = params.verifyBusiness.split(',');
									params.verifyBusinessType = 2;
								} else {
									params.verifyBusinessType = 1;
									params.verifyBusiness = [];
								}
							}

							// 核销商户
							switch (params.verifyMerchant) {
								case 1:
								case 2:
									params.verifyMerchantList = [];
									break;
								case 3:
									params.verifyMerchantList.forEach(v => {
										v.merchant = 'M-' + v.merchant;
										v.shop = v.shop ? v.shop.split(',') : [];
									});
									break;
							}

							// 格式化availableTime 独立数据
							params.date = [params.startTime, params.endTime];
							params.availableTime.availablePeriodWeek = [];
							params.availableTime.availablePeriodDay = [];
							params.availableTime.availableDateList = [{
								date: null
							}];
							if (params.availableTime.timeType === 5) {
								params.availableTime.days = null;
							}
							if (params.availableTime.timeType === 1 || params.availableTime.timeType === 5) {
								params.availableTime.availablePeriod = null;
								params.availableTime.dateList = null;
								params.availableTime.startMinute1 = null;
								params.availableTime.startMinute2 = null;
								params.availableTime.startMinute3 = null;
								params.availableTime.endMinute1 = null;
								params.availableTime.endMinute2 = null;
								params.availableTime.endMinute3 = null;
							} else if (params.availableTime.timeType === 2) {
								params.availableTime.availablePeriodWeek = params.availableTime
									.availablePeriod ? params.availableTime.availablePeriod.split(',') : [];
							} else if (params.availableTime.timeType === 3) {
								params.availableTime.availablePeriodDay = params.availableTime
									.availablePeriod ? params.availableTime.availablePeriod.split(',') : [];
							} else if (params.availableTime.timeType === 4) {
								const dateListArr = [];
								params.availableTime.dateList.split(',').forEach(v => {
									const date = v.split(':');
									dateListArr.push({
										date: [date[0], date[1]]
									});
								});
								params.availableTime.availableDateList = dateListArr;
							}
							// 格式化availableTime 通用数据
							if (params.availableTime.timeType !== 1 && params.availableTime.timeType !== 5) {
								params.availableTime.days = null;
								const timeListArr = [];
								for (let i = 0; i < 3; i++) {
									if (params.availableTime[`startMinute${i + 1}`] || params.availableTime[
											`endMinute${i + 1}`]) {
										timeListArr.push({
											time: [
												this.$options.filters.mm2HHmm(params.availableTime[
													`startMinute${i + 1}`]),
												this.$options.filters.mm2HHmm(params.availableTime[
													`endMinute${i + 1}`])
											]
										});
									}
								}
								params.availableTime.availableTimeList = timeListArr;
							} else {
								params.availableTime.availableTimeList = [{
									time: ['00:00', '23:59']
								}];
							}

							// 优惠标签
							params.discountTag = params.discountTag ? params.discountTag.split(',') : [];

							// 功能按钮
							params.functionButtonConfig = params.functionButton ?
								JSON.parse(params.functionButtonConfig) : {
									word: null,
									appId: null,
									page: null
								};
							console.log('格式化完成', params);
							this.form = params;
						})
						.finally(() => {
							resolve();
						});
				});
			},

			/**
			 * 按钮组
			 */
			// 新增日期
			addAvailableDateList() {
				this.form.availableTime.availableDateList.push({
					date: ''
				});
			},

			// 删除日期
			delAvailableDateList(index) {
				this.form.availableTime.availableDateList.splice(index, 1);
				this.$refs.form.validateField('availableDateList');
			},

			// 新增时间
			addAvailableTimeList() {
				this.form.availableTime.availableTimeList.push({
					time: ''
				});
			},

			// 删除时间
			delAvailableTimeList(index) {
				this.form.availableTime.availableTimeList.splice(index, 1);
				this.$refs.form.validateField('availableTime.availableTimeList');
			},

			// 打开本商户门店
			// 打开商户
			openDialogMerchantsTree(mode) {
				let checkedIds = [];
				let treeData = [];
				if (mode === 'sendMerchant') {
					treeData = this.allMchList;
					this.form.sendMerchantList.forEach(v => {
						checkedIds.push(v.merchant);
					});
				} else if (mode === 'verifyMerchant') {
					treeData = this.allMchShopList;
					this.form.verifyMerchantList.forEach(v => {
						checkedIds = checkedIds.concat(v.shop);
					});
				}
				this.$refs.dialogMerchantsTree.open({
					treeData,
					checkedIds
				}).then(res => {
					console.log('选择商户', res);
					if (mode === 'sendMerchant') {
						this.$refs.form.clearValidate(['sendMerchantList']);
						this.form.sendMerchantList = res;
					} else if (mode === 'verifyMerchant') {
						this.$refs.form.clearValidate(['verifyMerchantList']);
						this.form.verifyMerchantList = res;
					}
				});
			},

			// 关闭优惠标记
			closeDiscountTag(index) {
				this.form.discountTag.splice(index, 1);
			},

			// 新增优惠标签
			addDiscountTag() {
				const inputValue = this.discountTagInputValue;
				if (inputValue) {
					this.form.discountTag.push(inputValue);
					this.form.discountTag = [...new Set(this.form.discountTag)];
					this.discountTagInputValue = '';
				}
			},

			// 上传图片之前
			handleImgBefore(file, size) {
				return this.beforeUploadImg(file, this, 0, 0, size);
			},

			// 上传图片成功
			handleImgSuccess(res, file, type) {
				console.log(type);
				if (res.code === 0) {
					this.form[type] = res.data.path;
					this.$refs.form.clearValidate([type]);
				} else {
					this.$message.error(res.msg);
				}
			},

			// 修改步骤
			changeStep(mode = 'add') {
				if (mode === 'add') {
					if (this.step === 2) {
						this.submit(mode);
						return;
					}
					this.step += 1;
				} else {
					this.step -= 1;
				}
			},

			// 保存
			submit: function(mode = 'save', saveType) {
				// 判断是否是查看详细
				this.$refs.form.validate((valid, error) => {
					if (!valid) {
						console.log('valid false', error);
						const errorArr = Object.keys(error);
						const propObj = {
							0: [
								'cardName',
								'times',
								'denomination',
								'date',
								'availableTime.days',
								'availableTime.availablePeriodWeek',
								'availableTime.availablePeriodDay',
								'availableTime.availableDateList',
								'availableTime.availableTimeList',
								'description'
							],
							1: ['maxUseDay', 'maxUseWeek', 'maxUseMonth', 'verifyMerchant',
								'verifyMerchantList'
							],
							2: ['theme', 'functionButtonConfig.word', 'functionButtonConfig.appId',
								'functionButtonConfig.page'
							]
						};

						let errStep = [];
						errorArr.forEach(v => {
							for (const key in propObj) {
								if (propObj[key].includes(v)) {
									errStep.push(key);
								}
							}
						});
						errStep = [...new Set(errStep)];
						if (errStep.includes('0')) {
							this.step = 0;
						} else if (errStep.includes('1')) {
							this.step = 1;
						} else if (errStep.includes('2')) {
							this.step = 2;
						}
						this.$message.warning('请补充完整信息');
					} else {
						console.log('valid true', this.form);
						// 提交表单 处理相关数据
						const params = JSON.parse(JSON.stringify(this.form));
						// 次卡
						if (['times'].includes(params.cardType)) {
							params.discountTag = '';
							params.verifyBusiness = '';
							// 限制
							if (!params.maxUseDayChecked) params.maxUseDay = 0;
							if (!params.maxUseWeekChecked) params.maxUseWeek = 0;
							if (!params.maxUseMonthChecked) params.maxUseMonth = 0;
						}
						// 礼品卡
						if (['gift'].includes(params.cardType)) {
							params.denomination = this.$math.mul(params.denomination, 100, 0);
							// 核销业务
							params.verifyBusiness = params.verifyBusinessType === 1 ? '' : params
								.verifyBusiness.join();
							// 优惠标签
							params.discountTag = params.discountTag.join();
							if (params.maxUseDayChecked) params.maxUseDay = this.$math.mul(params.maxUseDay,
								100, 0);
							if (params.maxUseWeekChecked) params.maxUseWeek = this.$math.mul(params.maxUseWeek,
								100, 0);
							if (params.maxUseMonthChecked) params.maxUseMonth = this.$math.mul(params
								.maxUseMonth, 100, 0);
						}

						delete params.maxUseDayChecked;
						delete params.maxUseWeekChecked;
						delete params.maxUseMonthChecked;

						// 核销商户
						switch (params.verifyMerchant) {
							case 1:
							case 2:
								params.verifyMerchantList = [];
								break;
							case 3:
								params.verifyMerchantList.forEach(v => {
									v.merchant = String(v.merchant).replace('M-', '');
									v.shop = v.shop.join();
								});
								break;
						}

						// 格式化date
						params.startTime = params.date[0];
						params.endTime = params.date[1];
						delete params.date;
						// 格式化availableTime 独立数据
						if (params.availableTime.timeType === 1) {
							params.availableTime.availablePeriod = '';
							params.availableTime.dateList = '';
							params.availableTime.startMinute1 = '';
							params.availableTime.startMinute2 = '';
							params.availableTime.startMinute3 = '';
							params.availableTime.endMinute1 = '';
							params.availableTime.endMinute2 = '';
							params.availableTime.endMinute3 = '';
						} else if (params.availableTime.timeType === 2) {
							params.availableTime.availablePeriod = params.availableTime.availablePeriodWeek
								.join();
						} else if (params.availableTime.timeType === 3) {
							params.availableTime.availablePeriod = params.availableTime.availablePeriodDay
								.join();
						} else if (params.availableTime.timeType === 4) {
							const dateListArr = [];
							params.availableTime.availableDateList.forEach(v => {
								if (v && v.date.length === 2) {
									dateListArr.push(v.date[0] + ':' + v.date[1]);
								}
							});
							params.availableTime.dateList = dateListArr.join();
						}
						// 格式化availableTime 通用数据
						if (params.availableTime.timeType !== 1) {
							params.availableTime.days = '';
							params.availableTime.availableTimeList.forEach((v, i) => {
								if (v && v.time.length === 2) {
									params.availableTime[`startMinute${i + 1}`] = this.$momentMini
										.duration(v.time[0]).asMinutes();
									params.availableTime[`endMinute${i + 1}`] = this.$momentMini
										.duration(v.time[1]).asMinutes();
								}
							});
						}
						delete params.availableTime.availablePeriodWeek;
						delete params.availableTime.availablePeriodDay;
						delete params.availableTime.availableDateList;
						delete params.availableTime.availableTimeList;

						// 品牌名称 归属商户
						params.brandName = params.brandName || this.activeBusinessInfo.name;

						// 功能按钮
						params.functionButtonConfig = params.functionButton ? JSON.stringify(params
							.functionButtonConfig) : '';

						this.submitForm = params;
						console.log('提交的表单数据', params);
						if (mode === 'add') {
							this.step += 1;
						} else {
							this.save(params, saveType);
						}
					}
				});
			},

			// 保存
			save(params, saveType) {
				this.loading = true;
				if (saveType === 'draft') {
					console.log('返回草稿箱');
					saveCard(params)
						.then(res => {
							this.$notify({
								title: '成功',
								message: '保存成功',
								type: 'success',
								duration: 2000,
								offset: 40
							});
							this.$router.push({
								name: 'CardsAndOfferManageCard',
								params: {
									saveType
								}
							});
						})
						.finally(() => {
							this.loading = false;
						});
				} else {
					saveAndOpenUpCard(params)
						.then(res => {
							this.$notify({
								title: '成功',
								message: '保存成功',
								type: 'success',
								duration: 2000,
								offset: 40
							});
							this.$router.push({
								name: 'CardsAndOfferManageCard',
								params: {
									saveType
								}
							});
						})
						.finally(() => {
							this.loading = false;
						});
				}
			},

			// 返回
			back() {
				this.$router.go(-1);
			}

			/**
			 * 状态组
			 */
			/**
			 * 方法组
			 */
		}
	};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
	/* 通用类 */
	/* 布局 */
	.w-170 {
		width: 170px;
	}

	.w-200 {
		width: 200px;
	}

	.w-300 {
		width: 300px;
	}

	.w-400 {
		width: 400px;
	}

	.w-400-h-32 {
		width: 400px;
		height: 32px;
	}

	.last-dot:last-child .dot {
		display: none;
	}

	.el-tag {
		margin-right: 10px;
		margin-bottom: 10px;
	}

	/* 步骤 */
	.step-container {
		max-width: 800px;
		margin: 10px 0 30px;
		padding-left: 100px;
	}

	/* 嵌套内盒子 */
	.nest-card-box {
		width: 60%;
		min-width: 600px;
		max-width: 800px;

		.el-card {
			margin-bottom: 10px;
		}
	}

	/* 提示文本 */
	.tips-text {
		color: $light-font-color;
		line-height: 1.7;
	}

	/* 月日期盒子 */
	.day-box {
		width: 380px;
		display: flex;
		flex-wrap: wrap;

		::v-deep {
			.el-checkbox-button .el-checkbox-button__inner {
				width: 50px;
				margin: 2px 4px 2px 0;
				border: 1px solid #dcdfe6;
				border-radius: 0;
			}
		}
	}

	/* 主题 */
	.theme-picker-dropdown {
		::v-deep {
			.el-color-dropdown__main-wrapper {
				display: none;
			}
		}
	}

	/* 上传图片 */
	.upload-container {
		display: flex;

		.el-icon-plus {
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 36px;
			color: #8c939d;
		}

		.img {
			display: block;
		}
	}
</style>
